import React, { useEffect } from 'react';
import { Modal, Form, Input, Row, Col } from 'antd';

const FormModal = ({ props = {} }) => {
  const [form] = Form.useForm();
  const { title, width, visible, items, row, col, isOpenDialog, onSubmit, onCallback } = props;

  // 动态生成表单布局
  const formItems = () => {
    if (!items || items.length === 0) return null;

    const rows = [];
    const cols = Math.min(Math.max(1, col), 4); // 限制每行列数在1-4之间
    const span = 24 / cols; // 计算每列宽度

    for (let i = 0; i < items.length;) {
      const formCols = [];
      for (let j = 0; j < cols && i < items.length; j++, i++) {
        formCols.push(
          <Col key={j} span={span}>
            <Form.Item
              label={items[i].label}
              name={items[i].name}
              rules={items[i].rules || []}
              validateTrigger={items[i].validateTrigger}
            >
              {typeof items[i].render === 'function'
                ? items[i].render(row[items[i].name], row)
                : items[i].render || <Input placeholder={`请输入${items[i].label}`} allowClear={true} disabled={items[i]?.disabled} />}
            </Form.Item>
          </Col>
        );
      }
      rows.push(
        <Row key={i} gutter={16}>
          {formCols}
        </Row>
      );
    }

    return rows;
  };

  const onSubmitHandler = () => {
    form.validateFields().then(model => {
      onCallback(model, onSubmit);
      onCancelHandler();
    });
  }

  const onCancelHandler = () => {
    form.resetFields();
    isOpenDialog();
  }

  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        ...row,
      });
    }
  }, [visible, row]);

  return (
    <Modal
      title={title}
      width={width}
      open={visible}
      onOk={onSubmitHandler}
      onCancel={onCancelHandler}
      bodyProps={{ style: { padding: '8px 30px 0 0px' } }}
    >
      <Form
        form={form}
        name="form"
        labelCol={{ xs: 24, sm: 10, md: 8, lg: 6 }}
        labelAlign='right'
      >
        <Form.Item key="id" name="id" hidden>
          <Input />
        </Form.Item>
        {formItems()}
      </Form>
    </Modal>
  );
};

export default FormModal;